<template>
  <div>
    <!-- 添加表单 -->
    <el-form ref="addFromRef" label-position="top" :model="addForm" :rules="addFromRules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addForm.username" clearable></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addForm.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="addForm.password" clearable></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="passwordConfirm">
        <el-input type="password" v-model="addForm.passwordConfirm" clearable></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="addForm.age" clearable></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="addForm.gender">
          <el-radio value="1"> 男 </el-radio>
          <el-radio value="2"> 女 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="addForm.email" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="addForm.phone" clearable></el-input>
      </el-form-item>
      <el-form-item label="部门">
        <el-input v-model="addForm.department" clearable></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <!-- 上传 -->
        <el-upload list-type="picture" :auto-upload="false" :limit="1"
          v-model:file-list="addForm.avatar" accept=".jpg,.png">
          <el-button :disabled="addForm.avatar.length !== 0" size="small">选择头像</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="saveAddUser">保存</el-button>
        <el-button type="info" size="small" @click="cancelAddForm">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, shallowRef } from 'vue'

import { addUserApi, getUsersOneApi } from '@/api/users';

const emit = defineEmits(['cancelSave', 'successSave']);

const addFromRef = shallowRef(null);


const addForm = reactive({
  username: '',
  gender: '1',
  name: '',
  age: '',
  phone: '',
  email: '',
  department: '',
  avatar: [],
  password: '',
  passwordConfirm: ''
})

const validUsername = (rule, value, cb) => {
  const reg = /^\w{2,18}$/
  if (reg.test(value)) {
    cb()
  } else {
    cb(new Error('用户名必须3-18个字符'))
  }
}
const validName = (rule, value, cb) => {
  const reg = /^\w{2,18}$/
  if (reg.test(value)) {
    cb()
  } else {
    cb(new Error('姓名必须3-18个字符'))
  }
}

const validAge = (rule, value, cb) => {
  if (value >= 10 && value <= 80) {
    cb()
  } else {
    cb(new Error('年龄10-80岁'))
  }
}
const validEmail = (rule, value, cb) => {
  const reg =
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  if (reg.test(value)) {
    cb()
  } else {
    cb(new Error('邮箱格式错误'))
  }
}
const validPhone = (rule, value, cb) => {
  const reg = /^(?:(?:\+|00)86)?1\d{10}$/
  if (reg.test(value)) {
    cb()
  } else {
    cb(new Error('手机格式错误'))
  }
}

const validServePhone = async (rule, value, cb) => {
  try {
    await getUsersOneApi('phone', value)
    cb(new Error('手机已经存在'))
  } catch (error) {
    cb()
  }
}
// 服务器端验证
const addFromRules = reactive({
  username: [
    { required: true, message: '用户名必须填写' },
    { validator: validUsername },
    {
      validator: async (rule, value, cb) => {
        try {
          await getUsersOneApi('username', value)
          cb(new Error('用户名已经存在'))
        } catch (error) {
          cb()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [{ required: true, message: '密码必须填写' }, {
    validator: (rules, value, cb) => {
      if (/^.{8,18}$/.test(value)) {
        cb();
      } else {
        cb(new Error('密码必须8-18位'))
      }
    }
  }],
  passwordConfirm: [{ required: true, message: '必须填写' }, {
    validator: (rules, value, cb) => {
      if (addForm.password === value) {
        cb();
      } else {
        cb(new Error('两次密码输入不一致'))
      }
    }
  }],
  name: [{ required: true, message: '姓名必须填写' }, { validator: validName }],
  age: [{ required: true, message: '年龄必须填写' }, { validator: validAge }],
  email: [
    { required: true, message: '邮箱必须填写' },
    { validator: validEmail },
    {
      validator: async (rule, value, cb) => {
        try {
          await getUsersOneApi('email', value)
          cb(new Error('邮箱已经存在'))
        } catch (error) {
          cb()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '手机必须填写' },
    { validator: validPhone },
    {
      validator: validServePhone,
      trigger: 'blur'
    }
  ]
})


// 添加用户
async function saveAddUser() {
  try {
    await addFromRef.value.validate()

    const fd = new FormData()
    fd.append('username', addForm.username)
    fd.append('email', addForm.email)
    fd.append('emailVisibility', true)
    fd.append('password', addForm.password)
    fd.append('passwordConfirm', addForm.passwordConfirm)
    fd.append('name', addForm.name)
    fd.append('phone', addForm.phone)
    fd.append('gender', addForm.gender)
    fd.append('age', addForm.age)
    fd.append('avatar', addForm.avatar[0].raw)
    await addUserApi(fd);

    emit('success-save');
    // 重置
    addFromRef.value.resetFields();
  } catch (error) {
    // console.log(error)
  }
}

// 取消
function cancelAddForm() {
  // 重置
  addFromRef.value.resetFields();
  emit('cancelSave');
}


</script>
